<?php
namespace app\home\controller;
use think\Controller;
use think\facade\Request;
use think\facade\Session;
use \app\home\model\User;
class Login extends Controller
{
    public function login()
    {
        $this->view->engine->layout(false);
        return view('login');
    }
    public function register()
    {
        $this->view->engine->layout(false);
        return view('register');
    }
    public function phone()
    {
        $param=Request::param();
        $validate=$this->validate($param,[
            'phone|手机号'=>'require|reg:1[3-9]\d{9}|unique:user,phone',
            'code|验证码'=>'require|length:4',
            'password|密码'=>'require|length:6,20|confirm:repassword'
        ]);
        if($validate!==true){
            $this->error($validate);
        }
        $code=cache('register_code_'.$param['phone']);
        if($code!=$param['code']){
            $this->error('验证码错误');
        }
        User::create($param,true);
        $this->redirect('/login');
    }
    public function sendCode()
    {
        $param=input();
        $code=mt_rand(1000,9999);
        $content="你注册的验证码是{$code}";
        cache('register_code_'.$param['phone'],$code);
        $res=['code'=>'200','msg'=>"短信发送成功","data"=>$content];
        json($res)->send();
        die;
    }
    public function do_login(){
        $param=Request::param();
        $validate=$this->validate($param,[
            'phone|手机号'=>'require',
            'password|密码'=>'require|length:6,20',
        ]);

        // $result=User::where('phone',$param['username'])->where('password',$param['password'])->find();
        $result=User::where(function($query) use($param){
            $query->where('phone',$param['username'])->whereOr('email',$param['username'])->whereOr('username',$param['username']);
        })->where('password',$param['password'])->find();
        if(!$result){
            $this->error('登录失败，用户名或密码错误');
        }else{
            // 赋值（当前作用域）
            Session('user_info',$result->toArray());
            // 赋值think作用域
            // Session::set('name','thinkphp','think');
            $this->success('登录成功','/');
        }
        // dump($param);
    }
}
